include ../config.mk

BOARD = allwinner-v853

ifndef BOARD_VARIANT
$(error Please define BOARD_VARIANT in config.mk)
endif

LONG_NAME += $(BOARD)$(BOARD_VARIANT_TAG)-$(PROJECT)

CFLAGS += -D$(BOARD_VARIANT)

BIN_FILE = $(LONG_NAME).bin
LIST_FILE = $(LONG_NAME).list
SREC_FILE = $(LONG_NAME).srec
ELF_FILE = $(LONG_NAME).elf
CMD_FILE = $(LONG_NAME).cmd
SCR_FILE = $(LONG_NAME).scr
UIMG_FILE = $(LONG_NAME).uimg

CC = $(TOOLCHAIN)/bin/$(TOOLCHAIN_PREFIX)gcc
AS = $(TOOLCHAIN)/bin/$(TOOLCHAIN_PREFIX)as
OBJDUMP = $(TOOLCHAIN)/bin/$(TOOLCHAIN_PREFIX)objdump
OBJCOPY = $(TOOLCHAIN)/bin/$(TOOLCHAIN_PREFIX)objcopy
LD = $(TOOLCHAIN)/bin/$(TOOLCHAIN_PREFIX)ld

CPUFLAGS += -mfpu=neon-vfpv4 -march=armv7-a -mfloat-abi=hard
ARCHFLAGS += -mtune=cortex-a7 -mhard-float

CFLAGS += $(CPUFLAGS) $(ARCHFLAGS) -Wall -O2 -nostdlib -nostartfiles -ffreestanding -I../_common
AFLAGS += $(CPUFLAGS)

LDSCRIPT ?= ../_common/$(BOARD).ld

.DEFAULT_GOAL := all

.PHONY: clean
clean:
	rm -f $(OBJECTS) $(BIN_FILE) $(LIST_FILE) $(SREC_FILE) $(ELF_FILE) $(SCR_FILE) $(CMD_FILE) $(UIMG_FILE)

$(ELF_FILE): $(LDSCRIPT) $(OBJECTS) $(LIBS_FILES)
	@echo LD $<
	@$(LD) $(OBJECTS) $(LIBS) -T $(LDSCRIPT) -o $@

$(CMD_FILE):
	@echo $@
	@/bin/echo -e "setenv image $(PXE_DIR)/$(LONG_NAME).bin\ntftpboot 0x42000000 $(PXE_SERVER):\$${image};go 0x42000000" >$(CMD_FILE)

.PHONY: all
all: $(ELF_FILE) $(BIN_FILE) $(LIST_FILE) $(SREC_FILE) $(UIMG_FILE)

.PHONY: install
install: $(BIN_FILE) $(SCR_FILE)
	scp $(SCR_FILE) $(PXE_DEST)/$(PXE_DIR)/
	scp $(BIN_FILE) $(PXE_DEST)/$(PXE_DIR)/$(LONG_NAME).bin

%.o: %.c
	@echo CC $<
	@$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

%.o: %.s
	@echo AS $<
	@$(AS) $< $(AFLAGS) -o $@

%.list: %.elf
	@echo LIST $<
	@$(OBJDUMP) -D $< > $@

%.srec: %.elf
	@echo SREC $<
	@$(OBJCOPY) --srec-forceS3 $< -O srec $@

%.bin: %.elf
	@echo BIN $<
	@$(OBJCOPY) $< -O binary $@

%.uimg: %.bin
	@echo UIMG $<
	@mkimage -A arm -C none -n "$(LONG_NAME)" -T kernel -a 0x42000000 -e 0x42000000 -d $(LONG_NAME).bin $@

%.scr: %.cmd
	@echo SCR $<
	@mkimage -C none -A arm -T script -d $< $@ >/dev/null


# Linux kernel style according to https://www.gnu.org/software/indent/manual/indent.html
linux_style = -nbad -bap -nbc -bbo -hnl -br -brs -c33 -cd33 -ncdb -ce -ci4 -cli0 \
  -d0 -di1 -nfc1 -i8 -ip0 -l80 -lp -npcs -nprs -npsl -sai -saf -saw -ncs -nsc \
  -sob -nfca -cp33 -ss -ts8 -il1
.PHONY: format
format:
	indent $(linux_style) *.c
